<template>
  <el-config-provider :locale="zhCn">
    <div class="takeover-settings">
      <!-- 筛选条件区域 -->
      <filter-form
        v-model="filterForm"
        :form-items="formItems"
        @search="handleSearch"
        @reset="resetFilter"
        @update:modelValue="handleFilterChange"
        label-width="100px"
      />

      <!-- 列表展示区域 -->
      <div class="table-section">
        <el-table :data="tableData" border style="width: 100%" v-loading="loading" class="custom-table">
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="主体信息" min-width="300" align="center">
            <template #default="{ row }">
              <ai-wechat-info :avatar-url="row.wechatUser?.userAvatarUrl || ''" :user-name="row.wechatUser?.userName || ''" />
            </template>
          </el-table-column>
          <el-table-column prop="wechatUser.gender" label="性别" width="80" align="center">
            <template #default="{ row }">
              {{ row.wechatUser?.gender === '0' ? '男' : '女' }}
            </template>
          </el-table-column>
          <el-table-column prop="aiModel.modelName" label="私有模型" min-width="120" show-overflow-tooltip>
            <template #default="{ row }">
              {{ row.aiModel?.modelName || '-' }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="isFile" label="文件投喂" width="100" align="center">
            <template #default="{ row }">
              <el-tag :type="row.isFile === '1' ? 'success' : 'info'">{{ row.isFile === '1' ? '是' : '否' }}</el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="chatMode" label="聊天模式" width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="getChatModeType(row.chatMode)">{{ getChatModeText(row.chatMode) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="标签" min-width="300" show-overflow-tooltip>
            <template #default="{ row }">
              <div v-if="row.fendLabelStr" class="friend-list">
                <el-tag v-for="friend in row.fendLabelStr.split(',')" :key="friend" size="small" type="success" class="friend-item">
                  {{ friend.trim() }}
                </el-tag>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="好友" min-width="300" show-overflow-tooltip>
            <template #default="{ row }">
              <div v-if="row.userListStr" class="tag-list">
                <el-tag v-for="tag in row.userListStr.split(',')" :key="tag" size="small" type="info" class="tag-item">
                  {{ tag.trim() }}
                </el-tag>
              </div>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column prop="wechatUser.userCreateTime" label="创建时间" min-width="160" show-overflow-tooltip />
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total" @pagination="handlePagination" />

      <!-- 新增/编辑对话框 -->
      <el-dialog v-model="dialogVisible" title="编辑配置" width="600px" destroy-on-close class="takeover-dialog">
        <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="takeover-form">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入用户名" disabled />
          </el-form-item>
          <el-form-item label="私有模型" prop="aiModelId">
            <el-select v-model="form.aiModelId" placeholder="请选择AI模型" class="w-full">
              <el-option v-for="model in modelList" :key="model.id" :label="model.modelName" :value="model.id" />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="文件投喂" prop="isFile">
            <el-radio-group v-model="form.isFile">
              <el-radio label="1">是</el-radio>
              <el-radio label="0">否</el-radio>
            </el-radio-group>
          </el-form-item> -->
          <el-form-item label="聊天模式" prop="chatMode">
            <el-radio-group v-model="form.chatMode">
              <el-radio label="1">人工</el-radio>
              <el-radio label="2">AI辅助</el-radio>
              <el-radio label="3">AI接管</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="接管模式" prop="type">
            <el-radio-group v-model="form.type" @change="handleTypeChange">
              <el-radio label="all">全部好友</el-radio>
              <el-radio label="custom">自定义</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="好友标签" prop="fendLabel" v-if="form.type === 'custom'">
            <tag-tag-input
              :selected-tags="selectedTagsList"
              placeholder="请选择标签"
              @click="tagSelectDialogVisible = true"
              @remove="handleRemoveTagFromSelected"
            />
            <tag-select-dialog
              v-model="tagSelectDialogVisible"
              :multiple="true"
              :selected-tags="selectedTagsList.map((tag) => tag.id)"
              title="选择标签"
              @confirm="handleTagSelectConfirm"
              @cancel="tagSelectDialogVisible = false"
            />
          </el-form-item>
          <el-form-item label="选择好友" prop="userList" v-if="form.type === 'custom'">
            <friend-tag-input
              :selected-friends="selectedFriendsList"
              placeholder="请选择好友"
              @click="friendSelectDialogVisible = true"
              @remove="handleRemoveFriendFromSelected"
            />
            <friend-select-dialog
              v-model="friendSelectDialogVisible"
              :multiple="true"
              :selected-friends="selectedFriendsList.map((f) => f.wxAccount || f.wx_id)"
              title="选择好友"
              @confirm="handleFriendSelectConfirm"
              @cancel="friendSelectDialogVisible = false"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </el-config-provider>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, Ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import type { FormInstance, FormRules } from 'element-plus';
import type { FormItem } from '@/components/FilterForm/index.vue';
import { getTakeoverList, updateTakeover } from '@/api/privateModel/takeoverSettings';
import { getModelList as getAITrainModelList } from '@/api/privateModel/aiTrain';
import FilterForm from '@/components/FilterForm/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import AiWechatInfo from '@/components/AiWechatInfo/index.vue';
import TagSelectDialog from '@/components/TagSelect/TagSelectDialog.vue';
import TagTagInput from '@/components/TagSelect/TagTagInput.vue';
import { getAllLabel } from '@/api/userRate/label';
import FriendTagInput from '@/components/FriendSelect/FriendTagInput.vue';
import FriendSelectDialog from '@/components/FriendSelect/FriendSelectDialog.vue';
import { contactsPage } from '@/api/wechat';

// 类型定义
interface WechatUser {
  id: number;
  wechatAccountId: string;
  myWxId: string;
  userOpenId: string;
  userWechatUserId: string | null;
  userName: string;
  userAvatarUrl: string;
  userEmail: string | null;
  userPhone: string | null;
  userCreateTime: string;
  userInfoUpdateTime: string;
  userStatus: string | null;
  remark: string | null;
  wxAccount: string | null;
  userAge: string | null;
  userBirthday: string | null;
  userQq: string | null;
  userAddress: string | null;
  userDescription: string | null;
  userCustomerSource: string | null;
  userAssignedEmployee: string | null;
  gender: string;
}

interface TakeoverConfig {
  id: number;
  wxId: string;
  aiModelId: number | null;
  isFile: string;
  chatMode: string;
  fendLabel: string | null;
  accountType: string | null;
  account: string | null;
  isUser: string | null;
  aiModel: any | null;
  userList: string | null;
  userListStr: string | null;
  fendLabelStr: string | null;
  wechatUser: WechatUser;
}

interface TakeoverListResponse {
  code: number;
  msg: string;
  data: {
    records: TakeoverConfig[];
    total: number;
    [key: string]: any;
  };
}

// 状态定义
const loading = ref(false);
const dialogVisible = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref<TakeoverConfig[]>([]);
const modelList = ref<any[]>([]);
const formRef = ref<FormInstance>();
const tagSelectDialogVisible = ref(false);
const selectedTagsList = ref<any[]>([]);
const tagList = ref<any[]>([]);
const selectedFriendsList: Ref<any[]> = ref([]);
const friendSelectDialogVisible = ref(false);

// 从本地存储获取wx_id
const wxIdFromProfile = computed(() => {
  const msgProfile = JSON.parse(localStorage.getItem('msgprofile') || '{}');
  return msgProfile.wx_id || '';
});

// 筛选表单
const filterForm = reactive({
  wxId: '',
  aiModelId: '',
  isFile: '',
  chatMode: '',
  fendLabel: '',
  accountType: ''
});

// 表单数据
const form = reactive({
  id: '',
  wxId: '',
  userName: '',
  aiModelId: '',
  isFile: '0',
  chatMode: '1',
  fendLabel: '',
  accountType: '',
  type: 'custom',
  userList: ''
});

// 表单验证规则
const customTagOrFriendValidator = (rule: any, value: any, callback: any) => {
  if (form.type !== 'custom') {
    callback();
    return;
  }
  if (!form.fendLabel && !form.userList) {
    callback(new Error('好友标签和选择好友至少填写一个'));
  } else {
    callback();
  }
};

const rules: FormRules = {
  userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  aiModelId: [{ required: true, message: '请选择AI模型', trigger: 'change' }],
  isFile: [{ required: true, message: '请选择是否开启文件投喂', trigger: 'change' }],
  chatMode: [],
  fendLabel: [{ validator: customTagOrFriendValidator, trigger: 'blur' }],
  userList: [{ validator: customTagOrFriendValidator, trigger: 'blur' }]
};

// 获取聊天模式文本
const getChatModeText = (mode: string) => {
  const modeMap: Record<string, string> = {
    '1': '人工',
    '2': 'AI辅助',
    '3': 'AI接管'
  };
  return modeMap[mode] || mode;
};

// 获取聊天模式标签类型
const getChatModeType = (mode: string) => {
  const typeMap: Record<string, string> = {
    '1': 'info',
    '2': 'warning',
    '3': 'success'
  };
  return typeMap[mode] || 'info';
};

// 表单项配置
const formItems = computed<FormItem[]>(() => [
  {
    label: '私有模型',
    prop: 'aiModelId',
    type: 'select',
    placeholder: '请选择AI模型',
    options: modelList.value.map((m: any) => ({ label: m.modelName, value: m.id }))
  },
  // {
  //   label: '文件投喂',
  //   prop: 'isFile',
  //   type: 'select',
  //   placeholder: '请选择',
  //   options: [
  //     { label: '是', value: '1' },
  //     { label: '否', value: '0' }
  //   ]
  // },
  {
    label: '聊天模式',
    prop: 'chatMode',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '人工', value: '1' },
      { label: 'AI辅助', value: '2' },
      { label: 'AI接管', value: '3' }
    ]
  }
  // {
  //   label: '好友标签',
  //   prop: 'fendLabel',
  //   type: 'input',
  //   placeholder: '请输入好友标签'
  // }
]);

// 获取列表数据（合并筛选和分页参数，去除空值）
const getList = async () => {
  loading.value = true;
  try {
    const params: Record<string, any> = {
      ...filterForm,
      current: currentPage.value,
      size: pageSize.value,
      wxId: filterForm.wxId || wxIdFromProfile.value // 优先筛选表单，否则用本地 wx_id
    };
    // 移除空值参数
    Object.keys(params).forEach((key) => {
      if (params[key] === '' || params[key] === undefined) {
        delete params[key];
      }
    });
    const res = (await getTakeoverList(params)) as unknown as TakeoverListResponse;
    if (res.code === 200 && res.data) {
      tableData.value = res.data.records;
      total.value = res.data.total;
    } else {
      ElMessage.error(res.msg || '获取列表失败');
    }
  } catch (error) {
    console.error('获取列表失败:', error);
    ElMessage.error('获取列表失败');
  } finally {
    loading.value = false;
  }
};

// 获取AI模型列表
const getModelList = async () => {
  try {
    const res = await getAITrainModelList({ current: 1, size: 100 });
    if (res.data && Array.isArray(res.data.records)) {
      modelList.value = res.data.records;
    }
  } catch (error) {
    console.error('获取AI模型列表失败:', error);
    ElMessage.error('获取AI模型列表失败');
  }
};

// 分页事件
const handlePagination = ({ pageNum, pageSize: size }: { pageNum: number; pageSize: number }) => {
  currentPage.value = pageNum;
  pageSize.value = size;
  getList();
};

// 查询
const handleSearch = () => {
  currentPage.value = 1;
  getList();
};

// 重置筛选
const resetFilter = () => {
  Object.keys(filterForm).forEach((key) => {
    filterForm[key as keyof typeof filterForm] = '';
  });
  filterForm.wxId = wxIdFromProfile.value; // 重置为本地 wx_id
  currentPage.value = 1;
  pageSize.value = 10;
  getList();
};

// 筛选条件变化
const handleFilterChange = (val: any) => {
  Object.keys(val).forEach((key) => {
    filterForm[key as keyof typeof filterForm] = val[key];
  });
};

// 编辑
const handleEdit = async (row: TakeoverConfig) => {
  Object.assign(form, {
    id: row.id,
    wxId: row.wxId,
    userName: row.wechatUser?.userName || '',
    aiModelId: row.aiModelId || '',
    isFile: row.isFile,
    chatMode: row.chatMode,
    fendLabel: row.fendLabel || '',
    accountType: row.accountType || '',
    type: row.fendLabel === 'all' ? 'all' : 'custom',
    userList: row.userList || ''
  });
  if (form.type === 'custom') {
    // 回显标签名
    if (row.fendLabel) {
      const ids = row.fendLabel.split(',');
      selectedTagsList.value = tagList.value.filter((tag) => ids.includes(tag.id));
    } else {
      selectedTagsList.value = [];
    }
    // 回显好友（查联系人列表并筛选）
    if (row.userList) {
      const wxIds = row.userList.split(',');
      try {
        const res = await contactsPage({ wxId: row.wxId, current: 1, size: 1000 });
        if (res.data && Array.isArray(res.data.records)) {
          selectedFriendsList.value = res.data.records
            .filter((item: any) => wxIds.includes(item.wxAccount))
            .map((item: any) => ({
              ...item,
              wx_id: item.wxAccount, // 兼容组件
              nick_name: item.userName, // 确保有nick_name字段
              first_nick_name: item.userName, // 确保有first_nick_name字段
              avatar: item.avatarUrl // 确保有avatar字段
            }));
        } else {
          selectedFriendsList.value = [];
        }
      } catch (e) {
        selectedFriendsList.value = [];
      }
    } else {
      selectedFriendsList.value = [];
    }
  } else {
    selectedTagsList.value = [];
    selectedFriendsList.value = [];
  }
  tagSelectDialogVisible.value = false;
  friendSelectDialogVisible.value = false;
  dialogVisible.value = true;
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const submitData = {
          id: Number(form.id),
          wxId: form.wxId,
          aiModelId: Number(form.aiModelId),
          isFile: form.isFile,
          chatMode: form.chatMode,
          fendLabel: form.type === 'all' ? 'all' : form.type === 'custom' ? form.fendLabel : '',
          accountType: form.accountType,
          userList: form.type === 'custom' ? selectedFriendsList.value.map((f: any) => f.wxAccount || f.wx_id).join(',') : ''
        };
        const res: any = await updateTakeover(submitData);
        if (res.code === 200) {
          ElMessage.success('修改成功');
          dialogVisible.value = false;
          getList();
        } else {
          ElMessage.error(res.msg || '修改失败');
        }
      } catch (error) {
        console.error('修改失败:', error);
        ElMessage.error('修改失败');
      }
    }
  });
};

// 处理标签选择
const handleTagSelectConfirm = (tags: any[]) => {
  selectedTagsList.value = tags;
  form.fendLabel = tags.map((t) => t.id).join(',');
  tagSelectDialogVisible.value = false;
};

const handleRemoveTagFromSelected = (tag: any) => {
  selectedTagsList.value = selectedTagsList.value.filter((t) => t.id !== tag.id);
  form.fendLabel = selectedTagsList.value.map((t) => t.id).join(',');
};

const handleFriendSelectConfirm = (friends: any[]) => {
  // 合并去重
  const wxIdSet = new Set(selectedFriendsList.value.map((f) => f.wxAccount || f.wx_id));
  friends.forEach((f) => {
    const wxId = f.wxAccount || f.wx_id;
    if (!wxIdSet.has(wxId)) {
      selectedFriendsList.value.push({
        ...f,
        wx_id: wxId,
        nick_name: f.userName || f.nick_name,
        first_nick_name: f.userName || f.first_nick_name,
        avatar: f.avatarUrl || f.avatar
      });
      wxIdSet.add(wxId);
    }
  });
  form.userList = selectedFriendsList.value.map((f) => f.wxAccount || f.wx_id).join(',');
  friendSelectDialogVisible.value = false;
};

const handleRemoveFriendFromSelected = (friend: any) => {
  selectedFriendsList.value = selectedFriendsList.value.filter((f) => (f.wxAccount || f.wx_id) !== (friend.wxAccount || friend.wx_id));
  form.userList = selectedFriendsList.value.map((f) => f.wxAccount || f.wx_id).join(',');
};

// 处理接管模式变化
const handleTypeChange = async (value: string) => {
  if (value === 'all') {
    try {
      // 根据聊天模式动态生成提示消息
      const getChatMode = () => {
        switch (form.chatMode) {
          case '1':
            return 'AI将自动回复所有消息';
          case '2':
            return 'AI将协助处理消息';
          case '3':
            return 'AI接管功能';
        }
      };

      const message = `选择"全部好友"将对该微信号的所有好友启用${getChatMode()}，这是一个重要操作，请确认您了解此操作的影响。`;

      await ElMessageBox.confirm(message, '重要提示', {
        confirmButtonText: '我已了解，继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: false,
        customClass: 'all-friends-confirm-dialog'
      });
      // 用户确认后，清空自定义选择的数据
      selectedTagsList.value = [];
      selectedFriendsList.value = [];
      form.fendLabel = '';
      form.userList = '';
    } catch {
      // 用户取消，恢复到自定义模式
      form.type = 'custom';
    }
  } else if (value === 'custom') {
    // 切换到自定义模式时，保持原有逻辑
    // 不清空已选择的标签和好友数据，让用户可以继续编辑
    // 如果之前是全部好友模式，则清空相关数据
    if (form.fendLabel === 'all') {
      form.fendLabel = '';
    }
  }
};

const fetchTags = async () => {
  try {
    const res = await getAllLabel();
    if (res.data) {
      tagList.value = res.data.map((item: any) => ({ id: item.id.toString(), label_name: item.label_name }));
    }
  } catch (error) {
    ElMessage.error('获取标签列表失败');
  }
};

// 初始化
onMounted(() => {
  getList();
  getModelList();
  fetchTags();
});
</script>

<style lang="scss" scoped>
.takeover-settings {
  padding: 20px;
  min-height: calc(100vh - 40px);

  .table-section {
    background-color: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

    .custom-table {
      :deep(.el-table__header) {
        th {
          background-color: #f5f7fa;
          color: #606266;
          font-weight: 600;
        }
      }

      :deep(.el-table__row) {
        &:hover {
          td {
            background-color: #f5f7fa;
          }
        }
      }
    }
  }

  .pagination-section {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 16px 0;

    .custom-pagination {
      :deep(.el-pagination__total) {
        margin-right: 16px;
      }

      :deep(.el-pagination__sizes) {
        margin-right: 16px;
      }
    }
  }
}

.takeover-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }

  .takeover-form {
    .el-form-item {
      margin-bottom: 22px;
    }

    .w-full {
      width: 100%;
    }
  }
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.tag-list,
.friend-list {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;

  .tag-item,
  .friend-item {
    margin: 0;
    max-width: 100px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}

// 全部好友确认对话框样式
:deep(.all-friends-confirm-dialog) {
  .el-message-box__header {
    .el-message-box__title {
      color: #e6a23c;
      font-weight: 600;
    }
  }

  .el-message-box__content {
    .el-message-box__message {
      font-size: 14px;
      line-height: 1.6;
      color: #606266;
    }
  }

  .el-message-box__btns {
    .el-button--primary {
      background-color: #e6a23c;
      border-color: #e6a23c;

      &:hover {
        background-color: #ebb563;
        border-color: #ebb563;
      }
    }
  }
}
</style>
